// 业务处理模块
const connection = require('./db.js')

const token = require('./token')

const logger = require('./log4')
module.exports = {
    loginApi: (req, res) => {
        const name = req.body.name;
        const password = req.body.password;
        const sql_isName = `select * from user where name = '${name}'`
        connection.query(sql_isName, name, (err, result) => {
            if (err) return res.send({ status: 500, message: err.message, data: null })
            if (result.length == 0) {
                res.send({ status: 201, message: '用户名不存在', data: null })
            } else if (result[0].password !== password) {
                res.send({ status: 201, message: '密码错误', data: null })
            } else {
                let user = {
                    name: name,
                    password: password
                }
                // 为用户此次登录添加token
                const userToken = token.createToken(user)
                result[0].token = userToken
                res.send({ status: 200, message: '成功', data: result })
            }

        })
    },
    registerApi: (req, res) => {
        const name = req.body.name;
        const password = req.body.password;
        const qqNum = req.body.qq;
        const userImg = `http://q1.qlogo.cn/g?b=qq&nk=${qqNum}&s=100 `
        // new Promise(function (resolve, reject) {
        //     request({
        //         url: `http://q1.qlogo.cn/g?b=qq&nk=${qqNum}&s=100 `,
        //         encoding: 'binary'
        //     }, function (err, res, body) {
        //         resolve(body);
        //     });
        // }).then(function (body) {
        //     fs.createWriteStream(path.join(__dirname, 'public/image', qqNum + '.png'));
        //     res.send({ status: 203, message: '成功', data: null })
        // })

        // 查找数据库中是否同名
        const sql_foundName = `select * from user where qqNum = '${qqNum}'`;
        // 向数据库写入注册信息
        const sql_setUser = `insert into user(name,password,qqNum,userImg) values (?,?,?,?)`
        connection.query(sql_foundName, (err, result) => {
            if (err) return res.send({ status: 500, message: err.message, data: null })
            if (result.length != 0) {
                res.send({ status: 201, message: 'QQ号码已注册', data: null })
                return
            }
            connection.query(sql_setUser, [name, password, qqNum, userImg], (err, result) => {
                if (err) return res.send({ status: 500, message: err.message, data: null })
                res.send({ status: 200, message: '成功', data: result })
            })
        })
    },
    classListApi: (req, res) => {
        const sql = 'select * from class'
        connection.query(sql, (err, result) => {
            if (err) return res.send({ status: 500, message: err.message, data: null })
            res.send({ status: 200, message: 'ok', data: result })
        })
    },
    writeArticleApi: (req, res) => {
        const uid = req.body.userId
        const classId = req.body.classId
        const contentHtml = req.body.contentHtml
        const name = req.body.name
        const time = new Date().getTime()
        let uname = ''
        let userImgSrc = ''
        const sql_setArticle = `insert into article(uname,classId,contentHtml,name,time,userImg) values (?,?,?,?,?,?)`
        const sql_getUserName = `select * from user where id = '${uid}'`
        connection.query(sql_getUserName, (err, ress) => {
            uname = ress[0].name
            userImgSrc = ress[0].userImg
            connection.query(sql_setArticle, [uname, classId, contentHtml, name, time, userImgSrc], (err, result) => {
                if (err) return res.send({ status: 500, message: err.message, data: null })
                res.send({ status: 200, message: '成功', data: null })
            })
        })

    },
    readArticleApi: (req, res) => {
        const classId = req.query.classId;
        const pageSize = req.query.pageSize;
        const pageNum = req.query.pageNum;
        let offset = (Number(pageNum) - 1) * Number(pageSize)
        let sql = ``
        if (classId == 0) {
            sql = `select * from article`
        } else {
            sql = `select * from article where classId = '${classId}' limit ${Number(pageSize)} offset ${offset}`
        }

        connection.query(sql, (err, result) => {
            if (err) return res.send({ status: 500, message: err.message, data: null })
            res.send({ status: 200, message: 'ok', data: result })
        })
    },
    getArticleApi: (req, res) => {
        const articleId = req.query.id
        let sql = `select * from article where articleId = '${articleId}'`

        connection.query(sql, (err, result) => {
            if (err) return res.send({ status: 500, message: err.message, data: null })
            res.send({ status: 200, message: 'ok', data: result })
        })
    },

    commentApi: (req, res) => {
        const uname = req.body.uname;
        const uid = req.body.uid;
        const utext = req.body.utext;
        const articleId = req.body.articleId;
        const time = new Date().getTime()
        let userImgSrc = ''
        let sql_user = `select * from user where id = '${uid}'`
        let sql = `insert into comment(uname,utext,articleId,time,userImg) values (?,?,?,?,?)`
        connection.query(sql_user, (err, ress) => {
            userImgSrc = ress[0].userImg
            connection.query(sql, [uname, utext, articleId, time, userImgSrc], (err, result) => {
                if (err) return res.send({ status: 500, message: err.message, data: null })
                res.send({ status: 200, message: '成功', data: null })
            })
        })


    },
    getCommentListApi: (req, res) => {
        const articleId = req.query.articleId;
        let sql = `select * from comment where articleId = '${articleId}'`
        connection.query(sql, (err, result) => {
            if (err) return res.send({ status: 500, message: err.message, data: null })
            res.send({ status: 200, message: '成功', data: result })
        })
    },
    delCommentApi: (req, res) => {
        const commentId = req.query.commentId;
        let sql = `delete from comment where commentId = '${commentId}'`
        connection.query(sql, commentId, (err, result) => {
            if (err) return res.send({ status: 500, message: err.message, data: null })
            res.send({ status: 200, message: '成功', data: result })
        })
    },
    uploadImgApi: (req, res) => {
        const file = req.file
        file.src = `http:// 49.234.40.172:8888/public/images/${file.filename}`
        res.send({ status: 200, message: '成功', data: file })
    },
    getUserImgApi: (req, res) => {
        let qqNum = req.query.qqNum;
        let sql = `select * from user where qqNum = '${qqNum}'`
        logger.info('12121212121hfuihewui和服务i和')
        connection.query(sql, (err, result) => {
            if (err) return res.send({ status: 500, message: err.message, data: null })
            res.send({ status: 200, message: '成功', data: result })
        })
    },
    updateUserImgApi: (req, res) => {
        const uid = req.body.uid;
        const src = req.body.src;

        let sql = `UPDATE user SET userImg = ? WHERE Id = '${uid}'`;
        connection.query(sql, [src], (err, result) => {
            if (err) return res.send({ status: 500, message: err.message, data: null })
            res.send({ status: 200, message: '成功', data: result })
        })
    }
}
